package dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import pojo.User;
import config.SqlConfig;


@Repository
public class UserDao {
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	static Logger logger = Logger.getLogger(UserDao.class.getName());
	
//	private String OpenId=null;
//	private Integer userId=null;
	
	/**
	 * 根据微信标识获取用户信息
	 * @param wxID
	 * @return
	 */
	public User getUserByWxID(String wxID) {
		final User user = new User();
		Object[] params = new Object[]{ wxID };
		jdbcTemplate.query(SqlConfig.queryUserIdByWxID, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				user.setUserID(rs.getInt("user_id"));
			}
		});
		if(user.getUserID() != -1)
			return user;
		return null;
	}
	
	/**
	 * 根据用户手机号获取用户的OpenId（微信识别号）
	 * @param wxID
	 * @return
	 */
	public String getOpenIdByUserMobileNum(String userMobileNum) {
		final String[] OpenId={""};
		Object[] params = new Object[]{ userMobileNum };
		jdbcTemplate.query(SqlConfig.queryUserOpenId, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				OpenId[0]=rs.getString("user_weChatNumber");
			}
		});
		//如果查为空报错
		//String openId=jdbcTemplate.queryForObject(SqlConfig.queryUserOpenId, params, String.class);
		return OpenId[0];
	}
	
	/**
	 * 根据用户手机号获取用户的Id
	 * @param wxID)(和上面的重复了)
	 * @return
	 */
	public Integer getUserIdByOpenId(String openId) {
		final Integer[] userId={null};
		Object[] params = new Object[]{ openId };
		jdbcTemplate.query(SqlConfig.queryUserIdByWxID, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				userId[0]=rs.getInt("user_id");
			}
		});
		//Integer userId=jdbcTemplate.queryForObject(SqlConfig.queryUserIdByWxID, params, Integer.class);
		return userId[0];
	}


}